<script setup>
import { ref, onMounted, watch,getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';
import { useUserStore } from '../plugins/pinia';
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const userId = userStore.userInfo.id;
let id_t = null;
let view_t = null;
// 接收父组件传入的书单 ID
const props = defineProps({
  selectedbookId: {
    type: Number, // 传入的书单 ID，如果没有传入则表示新建书单
    default: null,
  },
});

// 定义表单数据
const form = ref({
  title: '',
  content: '',
  star: 0,
  books: [], // 已选择的图书
});
const bookDetails = [];
// 图书列表（供选择框使用）
const bookOptions = ref([]);
const fileList = ref([]);
// 获取图书数据
const fetchBooks = async () => {
  try {
    const response = await proxy.$axios.get('/book'); // 假设获取所有图书的接口
    bookOptions.value = response.data.data;
    console.log(bookOptions.value)
  } catch (error) {
    console.error('Error fetching books:', error);
    ElMessage.error('获取图书列表失败');
  }
};

// 获取书单详情
const fetchBooklistDetail = async () => {
  if (!props.selectedbookId) return;
  else{ // 如果没有传入书单 ID，则不请求
  try {
    const response = await proxy.$axios.get(`/recommend/${props.selectedbookId}`); // 假设书单详情接口
    const data = response.data.data;
    form.value = {
      title: data.title,
      content: data.content,
      star: data.star,
      img_url:data.img_url,
      view_sum:data.view_sum,
      books: []
    };
    id_t = data.id
    view_t = data.view_sum
    if (data.img_url) {
      fileList.value = [
        {
          name: '当前图片',
          url: data.img_url,
        },
      ];
    }
    const response_booklist = await proxy.$axios.get(`/booklist/${props.selectedbookId}`);
    const booklistData = response_booklist.data.data;
    form.value.books = booklistData.map((item) => item.book_id);
  } catch (error) {
    console.error('Error fetching booklist detail:', error);
    ElMessage.error('获取书单详情失败');
  }
}
};

// 保存书单
const saveBooklist = async () => {
  try {
    if (props.selectedbookId) {
      // 编辑书单
      const formResponse = await proxy.$axios.put('/recommend', {
      id:id_t,
      user_id: userId,
      title: form.value.title,
      content: form.value.content,
      star: form.value.star,
      img_url: form.value.img_url,
      view_sum:view_t
      });
  // 获取当前书单的 ID
  const re_id = props.selectedbookId
  const response_booklist = await proxy.$axios.delete(`/booklist/${props.selectedbookId}`);
  // 构造书单与图书的关联数据
  const booksPayload = form.value.books.map((book_id) => ({
    re_id,
    book_id,
  }));

  // 提交图书关联数据到新的 API
  const booksResponse = await proxy.$axios.post('/booklist', booksPayload);

  ElMessage.success('书单已创建，图书已添加！');
} else {
      // 新建书单
      try {
  // 提交书单数据到当前的 API
  const formResponse = await proxy.$axios.post('/recommend', {
    user_id: userId,
    title: form.value.title,
    content: form.value.content,
    star: form.value.star,
    img_url: form.value.img_url,
  });

  // 获取当前书单的 ID
  const re_id = formResponse.data.data;

  // 构造书单与图书的关联数据
  const booksPayload = form.value.books.map((book_id) => ({
    re_id,
    book_id,
  }));
  console.log(booksPayload)

  // 提交图书关联数据到新的 API
  const booksResponse = await proxy.$axios.post('/booklist', booksPayload);

  ElMessage.success('书单已创建，图书已添加！');
} catch (error) {
  ElMessage.error('提交失败，请稍后再试！');
  console.error('提交错误:', error);
}
    }
    // 返回父组件
    emit('navigateToBooklist');
  } catch (error) {
    console.error('Error saving booklist:', error);
    ElMessage.error('保存书单失败');
  }
};

// 获取图书数据和书单详情
onMounted(() => {
  fetchBooks();
  fetchBooklistDetail();
});

// 触发返回父组件的事件
const emit = defineEmits(['navigateToBooklist']);

const handleUploadSuccess = (response, file) => {
  form.value.img_url = response; 
  ElMessage.success('图片上传成功');
};
</script>

<template>
  <div class="newbooklist-container" style="width: 500px; margin: 0 auto; padding: 20px;">
    <h2>{{ props.selectedbookId ? '编辑书单' : '新建书单' }}</h2>

    <!-- 表单 -->
    <el-form :model="form" label-width="100px">
      <!-- 标题 -->
      <el-form-item label="书单标题">
        <el-input v-model="form.title" placeholder="请输入书单标题"></el-input>
      </el-form-item>

      <!-- 内容 -->
      <el-form-item label="书单内容">
        <el-input
          type="textarea"
          v-model="form.content"
          placeholder="请输入书单内容"
          rows="4"
        ></el-input>
      </el-form-item>

      <!-- 评分 -->
      <el-form-item label="评分">
        <el-rate v-model="form.star" show-score text-color="#ff9900"></el-rate>
      </el-form-item>

      <!-- 图书选择 -->
      <el-form-item label="选择图书">
        <el-select
          v-model="form.books"
          multiple
          clearable
          placeholder="请选择图书"
          :options="bookOptions"
          option-label="name"
          option-value="id"
        >
          <el-option
            v-for="book in bookOptions"
            :key="book.id"
            :label="book.name"
            :value="book.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="图片">
        <el-upload
          action="http://localhost:8080/upload"
          list-type="picture-card"
          :file-list="fileList"
          :on-success="handleUploadSuccess"
          :limit="1"
          :on-exceed="() => ElMessage.warning('只能上传一张图片')"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>


      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="saveBooklist">保存书单</el-button>
        <el-button @click="$emit('navigateTorecommend')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.newbooklist-container {
  background-color: #f7f7f7;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
